package com.jf.blog_jf04.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jf.blog_jf04.bean.Userinfo;
import com.jf.blog_jf04.service.MessageService;
import com.jf.blog_jf04.service.UserinfoService;
import com.jf.blog_jf04.utils.HttpUtils;
import com.jf.blog_jf04.utils.MyConstants;
import com.jf.blog_jf04.utils.R;
import com.jf.blog_jf04.utils.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;

@Service
@Transactional
public class MessageServiceImpl implements MessageService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserinfoService userinfoService;

    @Value("${send.message}")
    private Boolean sendMessage;

    @Override
    public R registerSend(String phone) {
        if (sendMessage) {
            Userinfo userinfo = userinfoService.getOne(new QueryWrapper<Userinfo>().eq("phone", phone));
            if (userinfo != null) {
                throw new BusinessException("手机号已注册！");
            }
            return sendCode(phone);
        }
        return sendDefaultCode(phone);
    }

    @Override
    public R forgetSend(String phone) {
        if (sendMessage) {
            Userinfo userinfo = userinfoService.getOne(new QueryWrapper<Userinfo>().eq("phone", phone));
            if (userinfo == null) {
                throw new BusinessException("该用户不存在！");
            }
            return sendCode(phone);
        }
        return sendDefaultCode(phone);
    }

    private R sendCode(String phone) {
        String code = HttpUtils.getCode();
        String url = HttpUtils.formateUrl(phone, code);
        String jsonStr = HttpUtils.doGet(url);
        JSONObject json = JSON.parseObject(jsonStr);
        if (json.getInteger("error_code") == 0) {
            String sid = json.getJSONObject("result").getString("sid");
            redisTemplate.opsForValue().set(MyConstants.MESSAGE_KEY + sid + "_" + phone, code, Duration.ofMinutes(5));
            return R.success().put("sid", sid);
        }
        return R.error(json.getString("reason"));
    }

    private R sendDefaultCode(String phone) {
        redisTemplate.opsForValue().set(MyConstants.MESSAGE_KEY + "abcd_" + phone, "12345", Duration.ofMinutes(5));
        return R.success().put("sid", "abcd");
    }
}
